import React, { useState, useEffect, useCallback } from 'react';
import {
    Card,
    Button,
    Space,
    Tag,
    Row,
    Col,
    Typography,
    Image,
    Descriptions,
    Layout,
    Spin,
    Divider,
    List,
    Modal,
    Form,
    InputNumber,
    Popconfirm,
    App,
    Radio,
    Input,
    Avatar,
    Checkbox
} from 'antd';
import {
    ArrowLeftOutlined,
    UserOutlined,
    ShopOutlined,
    ClockCircleOutlined,
    EditOutlined,
    DollarOutlined,
    ClearOutlined,
    PrinterOutlined,
    PlusOutlined,
    MinusOutlined,
    DeleteOutlined,
    PercentageOutlined,
    UserAddOutlined
} from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import dayjs from 'dayjs';
import tradeService from '../../services/tradeService';
import userService from '../../services/userService';
import type { Trade, Order, ModifyTradeParams, BindUserParams, CheckoutParams, CheckoutPreviewResponse } from '../../services/tradeService';
import type { User } from '../../services/userService';
import { getFormattedErrorMessage } from '../../services/baseApi';
import './OrderDetailPage.css';

const { Title, Text } = Typography;
const { Search } = Input;

const OrderDetailPage: React.FC = () => {
    const navigate = useNavigate();
    const { id } = useParams<{ id: string }>();

    // 状态
    const [order, setOrder] = useState<Trade | null>(null);
    const [loading, setLoading] = useState(false);
    const [modifyModalVisible, setModifyModalVisible] = useState(false);
    const [priceModalVisible, setPriceModalVisible] = useState(false);
    const [bindUserModalVisible, setBindUserModalVisible] = useState(false);
    const [checkoutModalVisible, setCheckoutModalVisible] = useState(false);
    const [operationLoading, setOperationLoading] = useState(false);
    const [userSearchLoading, setUserSearchLoading] = useState(false);
    const [checkoutLoading, setCheckoutLoading] = useState(false);
    const [modifyForm] = Form.useForm();
    const [priceForm] = Form.useForm();
    const [bindUserForm] = Form.useForm();
    const [checkoutForm] = Form.useForm();
    const [selectedOrderItem, setSelectedOrderItem] = useState<Order | null>(null);
    const [searchUsers, setSearchUsers] = useState<User[]>([]);
    const [selectedUser, setSelectedUser] = useState<User | null>(null);
    const [checkoutPreview, setCheckoutPreview] = useState<CheckoutPreviewResponse | null>(null);

    const { message } = App.useApp();

    // 返回订单列表
    const handleBack = () => {
        navigate(-1)
    };

    // 加载订单详情
    const loadOrderDetail = useCallback(async () => {
        if (!id) {
            message.error('订单ID不存在');
            navigate('/orders');
            return;
        }

        setLoading(true);
        try {
            const response = await tradeService.getTradeDetail(Number(id));

            if (response.code === 0 && response.data) {
                setOrder(response.data as unknown as Trade);
            } else {
                message.error(response.message || '获取订单详情失败');
                navigate('/orders');
            }
        } catch (error) {
            message.error(getFormattedErrorMessage(error));
            navigate('/orders');
        } finally {
            setLoading(false);
        }
    }, [id, navigate]);

    // 修改订单
    const handleModifyOrder = () => {
        if (!order) return;

        // 初始化表单数据
        const initialValues = {
            totalAmount: order.payment.amount,
            discount: order.payment.discount
        };

        modifyForm.setFieldsValue(initialValues);
        setModifyModalVisible(true);
    };

    // 提交修改
    const handleModifySubmit = async () => {
        if (!order) return;

        try {
            const values = await modifyForm.validateFields();
            setOperationLoading(true);

            const modifyParams: ModifyTradeParams = {
                id: order.id,
                tableId: order.restaurantTable.id,
                tradeOrderList: order.orders.map(orderItem => ({
                    orderId: orderItem.id,
                    productId: orderItem.item.productId,
                    variantId: orderItem.item.variantId || 0,
                    quantity: orderItem.item.quantity
                })),
                totalAmount: values.totalAmount
            };

            const response = await tradeService.modifyTrade(modifyParams);

            if (response.code === 0) {
                message.success('订单修改成功');
                setModifyModalVisible(false);
                loadOrderDetail(); // 重新加载订单详情
            } else {
                message.error(response.message || '订单修改失败');
            }
        } catch (error) {
            message.error(getFormattedErrorMessage(error));
        } finally {
            setOperationLoading(false);
        }
    };

    // 修改商品数量
    const handleQuantityChange = async (orderItem: Order, newQuantity: number) => {
        if (!order || newQuantity <= 0) return;

        setOperationLoading(true);
        try {
            const updatedOrders = order.orders.map(item => ({
                orderId: item.id,
                productId: item.item.productId,
                variantId: item.item.variantId || 0,
                quantity: item.id === orderItem.id ? newQuantity : item.item.quantity,
                price: item.item.price
            }));

            // 计算新的总金额
            const totalAmount = updatedOrders.reduce((sum, item) => sum + (item.price * item.quantity), 0);

            const modifyParams: ModifyTradeParams = {
                id: order.id,
                tableId: order.restaurantTable.id,
                tradeOrderList: updatedOrders,
                totalAmount
            };

            const response = await tradeService.modifyTrade(modifyParams);

            if (response.code === 0) {
                message.success('商品数量修改成功');
                loadOrderDetail(); // 重新加载订单详情
            } else {
                message.error(response.message || '修改商品数量失败');
            }
        } catch (error) {
            message.error(getFormattedErrorMessage(error));
        } finally {
            setOperationLoading(false);
        }
    };

    // 删除商品
    const handleDeleteProduct = async (orderItem: Order) => {
        if (!order) return;

        setOperationLoading(true);
        try {
            const updatedOrders = order.orders
                .filter(item => item.id !== orderItem.id)
                .map(item => ({
                    orderId: item.id,
                    productId: item.item.productId,
                    variantId: item.item.variantId || 0,
                    quantity: item.item.quantity,
                    price: item.item.price
                }));

            // 计算新的总金额
            const totalAmount = updatedOrders.reduce((sum, item) => sum + (item.price * item.quantity), 0);

            const modifyParams: ModifyTradeParams = {
                id: order.id,
                tableId: order.restaurantTable.id,
                tradeOrderList: updatedOrders,
                totalAmount
            };

            const response = await tradeService.modifyTrade(modifyParams);

            if (response.code === 0) {
                message.success('商品删除成功');
                loadOrderDetail(); // 重新加载订单详情
            } else {
                message.error(response.message || '删除商品失败');
            }
        } catch (error) {
            message.error(getFormattedErrorMessage(error));
        } finally {
            setOperationLoading(false);
        }
    };

    // 获取商品原价（从订单项的payment.originAmount计算）
    const getProductOriginalPrice = (orderItem: Order): number => {
        // 从订单项的payment信息计算原价
        return orderItem.payment?.originAmount ? orderItem.payment.originAmount / orderItem.item.quantity : orderItem.item.price;
    };

    // 打开价格修改弹窗
    const handleOpenPriceModal = (orderItem: Order) => {
        setSelectedOrderItem(orderItem);
        const originalPrice = getProductOriginalPrice(orderItem);
        const currentTotalPrice = orderItem.item.price * orderItem.item.quantity;

        priceForm.setFieldsValue({
            priceType: 'discount',  // 默认选中折扣计算
            originalPrice: originalPrice,
            currentPrice: orderItem.item.price,
            newTotalPrice: currentTotalPrice,
            newPrice: orderItem.item.price,
            discount: originalPrice > 0 ? (orderItem.item.price / originalPrice * 10) : 10
        });
        setPriceModalVisible(true);
    };

    // 快速折扣计算
    const handleQuickDiscount = (discount: number) => {
        const originalPrice = priceForm.getFieldValue('originalPrice');
        const quantity = selectedOrderItem?.item.quantity || 1;
        const newPrice = (originalPrice * discount / 10);
        const newTotalPrice = newPrice * quantity;

        priceForm.setFieldsValue({
            newPrice: parseFloat(newPrice.toFixed(2)),
            newTotalPrice: parseFloat(newTotalPrice.toFixed(2)),
            discount: discount
        });
    };

    // 价格类型变化处理
    const handlePriceTypeChange = (type: string) => {
        const originalPrice = priceForm.getFieldValue('originalPrice');
        const quantity = selectedOrderItem?.item.quantity || 1;

        if (type === 'discount') {
            const discount = priceForm.getFieldValue('discount') || 10;
            const newPrice = (originalPrice * discount / 10);
            const newTotalPrice = newPrice * quantity;
            priceForm.setFieldsValue({
                newPrice: parseFloat(newPrice.toFixed(2)),
                newTotalPrice: parseFloat(newTotalPrice.toFixed(2))
            });
        } else {
            // 直接输入金额时，保持当前总价
            const currentTotalPrice = priceForm.getFieldValue('newTotalPrice') || (originalPrice * quantity);
            priceForm.setFieldsValue({ newTotalPrice: currentTotalPrice });
        }
    };

    // 折扣变化处理
    const handleDiscountChange = (discount: number | null) => {
        const originalPrice = priceForm.getFieldValue('originalPrice');
        const quantity = selectedOrderItem?.item.quantity || 1;

        if (discount && discount > 0) {
            const newPrice = (originalPrice * discount / 10);
            const newTotalPrice = newPrice * quantity;
            priceForm.setFieldsValue({
                newPrice: parseFloat(newPrice.toFixed(2)),
                newTotalPrice: parseFloat(newTotalPrice.toFixed(2))
            });
        }
    };

    // 总价变化处理
    const handleTotalPriceChange = (totalPrice: number | null) => {
        const quantity = selectedOrderItem?.item.quantity || 1;
        if (totalPrice && totalPrice > 0 && quantity > 0) {
            const newPrice = totalPrice / quantity;
            priceForm.setFieldsValue({ newPrice: parseFloat(newPrice.toFixed(2)) });

            // 如果是折扣模式，同时更新折扣
            const priceType = priceForm.getFieldValue('priceType');
            if (priceType === 'discount') {
                const originalPrice = priceForm.getFieldValue('originalPrice');
                if (originalPrice > 0) {
                    const discount = (newPrice / originalPrice * 10);
                    priceForm.setFieldsValue({ discount: parseFloat(discount.toFixed(1)) });
                }
            }
        }
    };

    // 提交价格修改
    const handlePriceSubmit = async () => {
        if (!order || !selectedOrderItem) return;

        try {
            const values = await priceForm.validateFields();
            setOperationLoading(true);

            // 使用总价计算单价，确保精度
            const finalPrice = values.newTotalPrice;

            // 保持所有商品的当前价格，只修改选中商品的价格
            const updatedOrders = order.orders.map(item => ({
                orderId: item.id,
                productId: item.item.productId,
                variantId: item.item.variantId || 0,
                quantity: item.item.quantity,
                price: item.id === selectedOrderItem.id ? finalPrice : null
            }));

            // 计算新的总金额
            const totalAmount = updatedOrders.reduce((sum, item) => sum + (item.price * item.quantity), 0);

            const modifyParams: ModifyTradeParams = {
                id: order.id,
                tableId: order.restaurantTable.id,
                tradeOrderList: updatedOrders,
                totalAmount
            };

            const response = await tradeService.modifyTrade(modifyParams);

            if (response.code === 0) {
                message.success('商品价格修改成功');
                setPriceModalVisible(false);
                setSelectedOrderItem(null);
                loadOrderDetail(); // 重新加载订单详情
            } else {
                message.error(response.message || '修改商品价格失败');
            }
        } catch (error) {
            message.error(getFormattedErrorMessage(error));
        } finally {
            setOperationLoading(false);
        }
    };

    // 搜索用户
    const handleSearchUsers = async (keyword: string) => {
        if (!keyword.trim()) {
            setSearchUsers([]);
            return;
        }

        setUserSearchLoading(true);
        try {
            const response = await userService.searchUsers(keyword, { page: 1, pageSize: 10 });
            if (response.code === 0 && response.data) {
                setSearchUsers(response.data.list);
            } else {
                setSearchUsers([]);
                message.error(response.message || '搜索用户失败');
            }
        } catch (error) {
            setSearchUsers([]);
            message.error(getFormattedErrorMessage(error));
        } finally {
            setUserSearchLoading(false);
        }
    };

    // 选择用户
    const handleSelectUser = (user: User) => {
        setSelectedUser(user);
        bindUserForm.setFieldsValue({
            userId: user.id,
            username: user.username,
            mobile: user.mobile
        });
    };

    // 打开绑定用户弹窗
    const handleOpenBindUserModal = () => {
        setBindUserModalVisible(true);
        setSearchUsers([]);
        setSelectedUser(null);
        bindUserForm.resetFields();
    };

    // 提交绑定用户
    const handleBindUserSubmit = async () => {
        if (!order || !selectedUser) {
            message.error('请选择要绑定的用户');
            return;
        }

        setOperationLoading(true);
        try {
            const bindParams: BindUserParams = {
                userId: selectedUser.id
            };

            const response = await tradeService.bindUser(order.id, bindParams);

            if (response.code === 0) {
                message.success('绑定用户成功');
                setBindUserModalVisible(false);
                setSelectedUser(null);
                loadOrderDetail(); // 重新加载订单详情
            } else {
                message.error(response.message || '绑定用户失败');
            }
        } catch (error) {
            message.error(getFormattedErrorMessage(error));
        } finally {
            setOperationLoading(false);
        }
    };

    // 打开结账弹窗
    const handleOpenCheckoutModal = () => {
        if (!order) return;

        // 初始化表单数据
        const initialValues = {
            useBalance: order.user ? true : false,
            useCredit: order.user ? true : false,
            payMethod: 'cash'
        };

        checkoutForm.setFieldsValue(initialValues);
        setCheckoutModalVisible(true);
        setCheckoutPreview(null);

        // 如果有用户，自动预览
        if (order.user) {
            handleCheckoutPreview(initialValues);
        }
    };

    // 预览结账
    const handleCheckoutPreview = async (values?: { useBalance?: boolean; useCredit?: boolean; payMethod?: string }) => {
        if (!order) return;

        const formValues = values || checkoutForm.getFieldsValue();
        setCheckoutLoading(true);

        try {
            const checkoutParams: CheckoutParams = {
                action: 'preview',
                useBalance: formValues.useBalance || false,
                useCredit: formValues.useCredit || false,
                payMethod: formValues.payMethod || 'cash'
            };

            const response = await tradeService.checkout(order.id, checkoutParams);

            if (response.code === 0 && response.data) {
                setCheckoutPreview(response.data);
            } else {
                message.error(response.message || '预览结账失败');
                setCheckoutPreview(null);
            }
        } catch (error) {
            message.error(getFormattedErrorMessage(error));
            setCheckoutPreview(null);
        } finally {
            setCheckoutLoading(false);
        }
    };

    // 执行结账
    const handleCheckoutSubmit = async () => {
        if (!order) return;

        try {
            const values = await checkoutForm.validateFields();
            setOperationLoading(true);

            const checkoutParams: CheckoutParams = {
                action: 'pay',
                useBalance: values.useBalance || false,
                useCredit: values.useCredit || false,
                payMethod: values.payMethod || 'cash'
            };

            const response = await tradeService.checkout(order.id, checkoutParams);

            if (response.code === 0) {
                message.success('结账成功');
                setCheckoutModalVisible(false);
                setCheckoutPreview(null);
                loadOrderDetail(); // 重新加载订单详情
            } else {
                message.error(response.message || '结账失败');
            }
        } catch (error) {
            message.error(getFormattedErrorMessage(error));
        } finally {
            setOperationLoading(false);
        }
    };

    // 清台
    const handleCancelOrder = async () => {
        if (!order) return;

        setOperationLoading(true);
        try {
            const response = await tradeService.cancelTrade(order.id);

            if (response.code === 0) {
                message.success('清台成功');
                navigate('/orders'); // 返回订单列表
            } else {
                message.error(response.message || '清台失败');
            }
        } catch (error) {
            message.error(getFormattedErrorMessage(error));
        } finally {
            setOperationLoading(false);
        }
    };

    // 打印制作分单
    const handlePrintTicket = async () => {
        if (!order) return;

        setOperationLoading(true);
        try {
            const response = await tradeService.printTicket(order.id);

            if (response.code === 0) {
                message.success('打印制作分单成功');
            } else {
                message.error(response.message || '打印制作分单失败');
            }
        } catch (error) {
            message.error(getFormattedErrorMessage(error));
        } finally {
            setOperationLoading(false);
        }
    };

    // 打印结账单
    const handlePrintCashier = async () => {
        if (!order) return;

        setOperationLoading(true);
        try {
            const response = await tradeService.printCashier(order.id);

            if (response.code === 0) {
                message.success('打印结账单成功');
            } else {
                message.error(response.message || '打印结账单失败');
            }
        } catch (error) {
            message.error(getFormattedErrorMessage(error));
        } finally {
            setOperationLoading(false);
        }
    };

    // 页面初始化加载
    useEffect(() => {
        loadOrderDetail();
    }, [loadOrderDetail]);

    // 订单状态标签
    const getStatusTag = (status: number) => {
        switch (status) {
            case 1:
                return <Tag color="processing">进行中</Tag>;
            case 2:
                return <Tag color="success">已完成</Tag>;
            default:
                return <Tag color="default">未知</Tag>;
        }
    };

    // 配送类型文本
    const getDeliveryTypeText = (deliveryType: number) => {
        switch (deliveryType) {
            case 1:
                return '堂食';
            case 2:
                return '外卖';
            default:
                return '未知';
        }
    };

    if (loading) {
        return (
            <Layout className="order-detail-layout">
                <div className="loading-container">
                    <Spin size="large" tip="加载订单详情中..." />
                </div>
            </Layout>
        );
    }

    if (!order) {
        return (
            <Layout className="order-detail-layout">
                <div className="error-container">
                    <Text type="secondary">订单不存在</Text>
                    <Button type="primary" onClick={handleBack} style={{ marginTop: 16 }}>
                        返回订单列表
                    </Button>
                </div>
            </Layout>
        );
    }

    return (
        <Layout className="order-detail-layout">
            {/* 统一页头 */}
            <div className="order-detail-header">
                <div className="header-left">
                    <Button
                        className="back-button"
                        type="text"
                        icon={<ArrowLeftOutlined />}
                        size="large"
                        onClick={handleBack}
                    />
                    <h1 className="page-title">订单详情</h1>
                </div>
                <div className="header-right">
                    <Space>
                        {/* 操作按钮 */}
                        {order && order.status === 1 && (
                            <>
                                <Button
                                    type="default"
                                    icon={<EditOutlined />}
                                    onClick={handleModifyOrder}
                                    loading={operationLoading}
                                >
                                    修改订单
                                </Button>
                                <Button
                                    type="primary"
                                    icon={<DollarOutlined />}
                                    onClick={handleOpenCheckoutModal}
                                    loading={operationLoading}
                                    disabled={order.paymentStatus === 1}
                                >
                                    结账
                                </Button>
                                <Popconfirm
                                    title="确定要清台吗？此操作将取消订单"
                                    onConfirm={handleCancelOrder}
                                    okText="确定"
                                    cancelText="取消"
                                >
                                    <Button
                                        danger
                                        icon={<ClearOutlined />}
                                        loading={operationLoading}
                                    >
                                        清台
                                    </Button>
                                </Popconfirm>
                                <Button
                                    type="default"
                                    icon={<PrinterOutlined />}
                                    onClick={handlePrintTicket}
                                    loading={operationLoading}
                                >
                                    打印制作分单
                                </Button>
                                <Button
                                    type="default"
                                    icon={<PrinterOutlined />}
                                    onClick={handlePrintCashier}
                                    loading={operationLoading}
                                >
                                    打印结账单
                                </Button>
                            </>
                        )}
                        {order && order.status === 2 && (
                            <Button
                                type="default"
                                icon={<PrinterOutlined />}
                                onClick={handlePrintCashier}
                                loading={operationLoading}
                            >
                                打印结账单
                            </Button>
                        )}
                        {getStatusTag(order.status)}
                    </Space>
                </div>
            </div>

            {/* 主要内容区域 */}
            <div className="order-detail-content">
                <Row gutter={24}>
                    {/* 左侧：订单基本信息 */}
                    <Col span={16}>
                        {/* 订单基本信息 */}
                        <Card title="订单信息" className="info-card">
                            <Descriptions column={2} size="middle">
                                <Descriptions.Item label="订单ID">{order.id}</Descriptions.Item>
                                <Descriptions.Item label="订单号">
                                    <Text code>{order.no}</Text>
                                </Descriptions.Item>
                                <Descriptions.Item label="餐桌">
                                    <Space>
                                        <ShopOutlined />
                                        <Text strong>{order.restaurantTable?.name}</Text>
                                    </Space>
                                </Descriptions.Item>
                                <Descriptions.Item label="用户">
                                    <Space>
                                        <UserOutlined />
                                        {order.user ? (
                                            <Text>{order.user.username}</Text>
                                        ) : (
                                            <Space>
                                                <Text type="secondary">未绑定会员</Text>
                                                {order.status === 1 && (
                                                    <Button
                                                        size="small"
                                                        icon={<UserAddOutlined />}
                                                        onClick={handleOpenBindUserModal}
                                                    >
                                                        绑定会员
                                                    </Button>
                                                )}
                                            </Space>
                                        )}
                                    </Space>
                                </Descriptions.Item>
                                <Descriptions.Item label="配送方式">{getDeliveryTypeText(order.deliveryType)}</Descriptions.Item>
                                <Descriptions.Item label="就餐人数">{order.actualSeats}人</Descriptions.Item>
                                <Descriptions.Item label="创建时间">
                                    <Space>
                                        <ClockCircleOutlined />
                                        <Text>{dayjs(order.createdAt).format('YYYY-MM-DD HH:mm:ss')}</Text>
                                    </Space>
                                </Descriptions.Item>
                                <Descriptions.Item label="支付时间">
                                    <Space>
                                        <ClockCircleOutlined />
                                        <Text>{order.payAt ? dayjs(order.payAt).format('YYYY-MM-DD HH:mm:ss') : '-'}</Text>
                                    </Space>
                                </Descriptions.Item>
                                <Descriptions.Item label="备注" span={2}>
                                    <Text>{order.remark || '无备注'}</Text>
                                </Descriptions.Item>
                            </Descriptions>
                        </Card>

                        {/* 订单商品列表 */}
                        <Card title="订单商品" className="products-card" style={{ marginTop: 24 }}>
                            <List
                                dataSource={order.orders}
                                renderItem={(orderItem: Order) => (
                                    <List.Item className="product-item">
                                        <Row gutter={16} style={{ width: '100%' }}>
                                            <Col span={3}>
                                                {orderItem.item.productImage ? (
                                                    <Image
                                                        src={orderItem.item.productImage}
                                                        width={80}
                                                        height={80}
                                                        style={{ objectFit: 'cover', borderRadius: 8 }}
                                                        placeholder={
                                                            <div className="image-placeholder">
                                                                <ShopOutlined />
                                                            </div>
                                                        }
                                                    />
                                                ) : (
                                                    <div className="image-placeholder">
                                                        <ShopOutlined />
                                                    </div>
                                                )}
                                            </Col>
                                            <Col span={6}>
                                                <div className="product-info">
                                                    <Title level={5} style={{ margin: 0, marginBottom: 4 }}>
                                                        {orderItem.item.productName}
                                                    </Title>
                                                    <div className="product-variant">
                                                        {orderItem.item.variantName && (
                                                            <Tag color="blue">
                                                                {orderItem.item.variantName}
                                                            </Tag>
                                                        )}
                                                    </div>
                                                    {/* <div style={{ marginTop: 8 }}>
                                                        <Text type="secondary">订单号: {orderItem.no}</Text>
                                                    </div> */}
                                                    <div style={{ marginTop: 4 }}>
                                                        <Text type="secondary">
                                                            创建时间: {dayjs(orderItem.createdAt).format('MM-DD HH:mm')}
                                                        </Text>
                                                    </div>
                                                </div>
                                            </Col>
                                            <Col span={3} style={{ textAlign: 'center' }}>
                                                <div className="quantity-info">
                                                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
                                                        {order.status === 1 ? (
                                                            <>
                                                                <Button
                                                                    size="small"
                                                                    icon={<MinusOutlined />}
                                                                    onClick={() => handleQuantityChange(orderItem, orderItem.item.quantity - 1)}
                                                                    disabled={orderItem.item.quantity <= 1 || operationLoading}
                                                                />
                                                                <Text strong style={{ fontSize: 16, minWidth: 30, textAlign: 'center' }}>
                                                                    {orderItem.item.quantity}
                                                                </Text>
                                                                <Button
                                                                    size="small"
                                                                    icon={<PlusOutlined />}
                                                                    onClick={() => handleQuantityChange(orderItem, orderItem.item.quantity + 1)}
                                                                    disabled={operationLoading}
                                                                />
                                                            </>
                                                        ) : (
                                                            <Text strong style={{ fontSize: 16 }}>×{orderItem.item.quantity}</Text>
                                                        )}
                                                    </div>
                                                </div>
                                            </Col>
                                            <Col span={3} style={{ textAlign: 'center' }}>
                                                <div className="price-info">
                                                    {(() => {
                                                        const originalPrice = getProductOriginalPrice(orderItem);
                                                        const currentPrice = orderItem.item.price;
                                                        const hasDiscount = Math.abs(originalPrice - currentPrice) > 0.01;

                                                        return (
                                                            <div>
                                                                {hasDiscount ? (
                                                                    <>
                                                                        <div style={{ marginBottom: 2 }}>
                                                                            <Text delete type="secondary" style={{ fontSize: 12 }}>
                                                                                ¥{originalPrice?.toFixed(2)}
                                                                            </Text>
                                                                        </div>
                                                                        <div>
                                                                            <Text strong style={{ fontSize: 14, color: '#ff4d4f' }}>
                                                                                ¥{currentPrice?.toFixed(2)}
                                                                            </Text>
                                                                        </div>
                                                                        <div style={{ marginTop: 2 }}>
                                                                            <Tag color="red">
                                                                                {((currentPrice / originalPrice) * 10)?.toFixed(1)}折
                                                                            </Tag>
                                                                        </div>
                                                                    </>
                                                                ) : (
                                                                    <Text strong style={{ fontSize: 14 }}>
                                                                        ¥{currentPrice.toFixed(2)}
                                                                    </Text>
                                                                )}
                                                                <div style={{ marginTop: 4 }}>
                                                                    <Text type="secondary" style={{ fontSize: 12 }}>单价</Text>
                                                                </div>
                                                            </div>
                                                        );
                                                    })()}
                                                </div>
                                            </Col>
                                            <Col span={4} style={{ textAlign: 'center' }}>
                                                <div className="amount-info">
                                                    {(() => {
                                                        const orderPayment = orderItem.payment;
                                                        const hasOrderDiscount = orderPayment && Math.abs(orderPayment.originAmount - orderPayment.amount) > 0.01;

                                                        return (
                                                            <div>
                                                                {hasOrderDiscount ? (
                                                                    <>
                                                                        <div style={{ marginBottom: 2 }}>
                                                                            <Text delete type="secondary" >
                                                                                原价：¥{orderPayment.originAmount.toFixed(2)}
                                                                            </Text>
                                                                        </div>
                                                                        <div style={{ marginTop: 2 }}>
                                                                            <Text>
                                                                                调整：¥{orderPayment.adjust.toFixed(2)}
                                                                            </Text>
                                                                        </div>
                                                                        <div style={{ marginTop: 2 }}>
                                                                            <Text>
                                                                                折扣：{orderPayment?.discount.toFixed(2)}
                                                                            </Text>
                                                                        </div>
                                                                        <div>
                                                                            <Text strong style={{ fontSize: 12, color: '#52c41a' }}>
                                                                                实付：¥{orderPayment.amount.toFixed(2)}
                                                                            </Text>
                                                                        </div>

                                                                    </>
                                                                ) : (
                                                                    <Text strong style={{ fontSize: 16, color: '#52c41a' }}>
                                                                        ¥{orderItem.item.totalAmount.toFixed(2)}
                                                                    </Text>
                                                                )}
                                                            </div>
                                                        );
                                                    })()}
                                                </div>
                                            </Col>
                                            <Col span={3}>
                                                {order.status === 1 && (
                                                    <Col span={6} style={{ textAlign: 'right' }}>
                                                        <div className="product-actions">
                                                            <Space>
                                                                <Button
                                                                    size="small"
                                                                    icon={<PercentageOutlined />}
                                                                    onClick={() => handleOpenPriceModal(orderItem)}
                                                                    disabled={operationLoading}
                                                                >
                                                                    改价
                                                                </Button>
                                                                <Popconfirm
                                                                    title="确定要删除这个商品吗？"
                                                                    onConfirm={() => handleDeleteProduct(orderItem)}
                                                                    okText="确定"
                                                                    cancelText="取消"
                                                                >
                                                                    <Button
                                                                        size="small"
                                                                        danger
                                                                        icon={<DeleteOutlined />}
                                                                        disabled={operationLoading}
                                                                    >
                                                                        删除
                                                                    </Button>
                                                                </Popconfirm>
                                                            </Space>
                                                        </div>
                                                    </Col>
                                                )}
                                            </Col>
                                        </Row>
                                    </List.Item>
                                )}
                            />
                        </Card>
                    </Col>

                    {/* 右侧：支付信息 */}
                    <Col span={8}>
                        <Card title="支付信息" className="payment-card">
                            <div className="payment-summary">
                                <div className="payment-item">
                                    <span className="payment-label">商品原价</span>
                                    <span className="payment-value">¥{order.payment.originAmount.toFixed(2)}</span>
                                </div>

                                <div className="payment-item">
                                    <span className="payment-label">调整</span>
                                    <span className="payment-value">¥{order.payment.adjust.toFixed(2)}</span>
                                </div>

                                <div className="payment-item">
                                    <span className="payment-label">折扣金额</span>
                                    <span className="payment-value negative">-¥{order.payment.discount.toFixed(2)}</span>
                                </div>


                                <div className="payment-item total">
                                    <span className="payment-label">实付金额</span>
                                    <span className="payment-value">¥{order.payment.amount.toFixed(2)}</span>
                                </div>

                                {(order.payment.balance > 0 || order.payment.credit > 0) && (
                                    <>
                                        <Divider style={{ margin: '16px 0' }} />
                                        <div className="payment-methods">
                                            <Title level={5}>支付方式</Title>
                                            {order.payment.balance > 0 && (
                                                <div className="payment-item">
                                                    <span className="payment-label">余额支付</span>
                                                    <span className="payment-value">¥{order.payment.balance.toFixed(2)}</span>
                                                </div>
                                            )}
                                            {order.payment.credit > 0 && (
                                                <div className="payment-item">
                                                    <span className="payment-label">积分支付</span>
                                                    <span className="payment-value">¥{order.payment.credit.toFixed(2)}</span>
                                                </div>
                                            )}
                                        </div>
                                    </>
                                )}
                            </div>
                        </Card>

                        {/* 用户信息 */}
                        {order.user && (
                            <Card title="用户信息" style={{ marginTop: 24 }}>
                                <Descriptions column={1} size="small">
                                    <Descriptions.Item label="用户名">{order.user.username}</Descriptions.Item>
                                    <Descriptions.Item label="手机号">{order.user.mobile || '-'}</Descriptions.Item>
                                    <Descriptions.Item label="余额">¥{order.user.balance.toFixed(2)}</Descriptions.Item>
                                    <Descriptions.Item label="积分">{order.user.credit}</Descriptions.Item>
                                </Descriptions>
                            </Card>
                        )}
                    </Col>
                </Row>
            </div>

            {/* 修改订单模态框 */}
            <Modal
                title="修改订单"
                open={modifyModalVisible}
                onOk={handleModifySubmit}
                onCancel={() => setModifyModalVisible(false)}
                confirmLoading={operationLoading}
                destroyOnClose
            >
                <Form
                    form={modifyForm}
                    layout="vertical"
                >
                    <Form.Item
                        label="折扣金额"
                        name="discount"
                        rules={[{ required: true, message: '请输入折扣金额' }]}
                    >
                        <InputNumber
                            min={0}
                            precision={2}
                            style={{ width: '100%' }}
                            placeholder="请输入折扣金额"
                            addonAfter="元"
                        />
                    </Form.Item>

                    <Form.Item
                        label="实付金额"
                        name="totalAmount"
                        rules={[{ required: true, message: '请输入实付金额' }]}
                    >
                        <InputNumber
                            min={0}
                            precision={2}
                            style={{ width: '100%' }}
                            placeholder="请输入实付金额"
                            addonAfter="元"
                        />
                    </Form.Item>
                </Form>
            </Modal>

            {/* 价格修改模态框 */}
            <Modal
                title={`修改价格 - ${selectedOrderItem?.item.productName || ''}`}
                open={priceModalVisible}
                onOk={handlePriceSubmit}
                onCancel={() => {
                    setPriceModalVisible(false);
                    setSelectedOrderItem(null);
                }}
                confirmLoading={operationLoading}
                destroyOnClose
                width={500}
            >
                {selectedOrderItem && (
                    <Form
                        form={priceForm}
                        layout="vertical"
                        initialValues={{
                            priceType: 'discount',
                            originalPrice: selectedOrderItem.item.price,
                            currentPrice: selectedOrderItem.item.price,
                            newTotalPrice: selectedOrderItem.item.price * selectedOrderItem.item.quantity,
                            newPrice: selectedOrderItem.item.price,
                            discount: 10
                        }}
                    >
                        <Form.Item
                            label="原价"
                            name="originalPrice"
                        >
                            <InputNumber
                                disabled
                                precision={2}
                                style={{ width: '100%' }}
                                addonAfter="元"
                            />
                        </Form.Item>

                        <Form.Item
                            label="修改方式"
                            name="priceType"
                        >
                            <Radio.Group onChange={(e) => handlePriceTypeChange(e.target.value)}>
                                <Radio value="amount">直接输入金额</Radio>
                                <Radio value="discount">按折扣计算</Radio>
                            </Radio.Group>
                        </Form.Item>

                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.priceType !== currentValues.priceType}
                        >
                            {({ getFieldValue }) => {
                                const priceType = getFieldValue('priceType');
                                return priceType === 'discount' ? (
                                    <>
                                        <Form.Item
                                            label="快速折扣"
                                        >
                                            <Space wrap>
                                                <Button size="small" onClick={() => handleQuickDiscount(9)}>9折</Button>
                                                <Button size="small" onClick={() => handleQuickDiscount(8.8)}>8.8折</Button>
                                                <Button size="small" onClick={() => handleQuickDiscount(8)}>8折</Button>
                                                <Button size="small" onClick={() => handleQuickDiscount(6)}>6折</Button>
                                            </Space>
                                        </Form.Item>
                                        <Form.Item
                                            label="折扣"
                                            name="discount"
                                            rules={[{ required: true, message: '请输入折扣' }]}
                                        >
                                            <InputNumber
                                                min={0.1}
                                                max={10}
                                                precision={1}
                                                step={0.1}
                                                style={{ width: '100%' }}
                                                addonAfter="折"
                                                onChange={handleDiscountChange}
                                            />
                                        </Form.Item>
                                    </>
                                ) : null;
                            }}
                        </Form.Item>

                        <Form.Item
                            label="新价格"
                            name="newPrice"
                            rules={[{ required: true, message: '请输入新价格' }]}
                        >
                            <InputNumber
                                min={0}
                                precision={2}
                                style={{ width: '100%' }}
                                placeholder="请输入新价格"
                                addonAfter="元"
                            />
                        </Form.Item>

                        <Form.Item
                            label="总价"
                            name="newTotalPrice"
                            rules={[{ required: true, message: '请输入总价' }]}
                        >
                            <InputNumber
                                min={0}
                                precision={2}
                                style={{ width: '100%' }}
                                placeholder="请输入总价"
                                addonAfter="元"
                                onChange={handleTotalPriceChange}
                            />
                        </Form.Item>

                        <div style={{ marginTop: 16, padding: 12, backgroundColor: '#f5f5f5', borderRadius: 6 }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                                <Text type="secondary">数量:</Text>
                                <Text>{selectedOrderItem.item.quantity} 份</Text>
                            </div>
                            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                                <Text type="secondary">单价:</Text>
                                <Text>¥{(priceForm.getFieldValue('newPrice') || 0).toFixed(2)}</Text>
                            </div>
                            <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 'bold' }}>
                                <Text strong>小计:</Text>
                                <Text strong style={{ color: '#52c41a' }}>
                                    ¥{(priceForm.getFieldValue('newTotalPrice') || 0).toFixed(2)}
                                </Text>
                            </div>
                        </div>
                    </Form>
                )}
            </Modal>

            {/* 绑定会员模态框 */}
            <Modal
                title="绑定会员"
                open={bindUserModalVisible}
                onOk={handleBindUserSubmit}
                onCancel={() => {
                    setBindUserModalVisible(false);
                    setSelectedUser(null);
                    setSearchUsers([]);
                }}
                confirmLoading={operationLoading}
                destroyOnClose
                width={600}
                okText="绑定"
                cancelText="取消"
                okButtonProps={{
                    disabled: !selectedUser
                }}
            >
                <Form
                    form={bindUserForm}
                    layout="vertical"
                >
                    <Form.Item
                        label="搜索会员"
                        help="请输入手机号或用户名搜索会员"
                    >
                        <Search
                            placeholder="请输入手机号或用户名"
                            allowClear
                            enterButton="搜索"
                            size="large"
                            loading={userSearchLoading}
                            onSearch={handleSearchUsers}
                        />
                    </Form.Item>

                    {searchUsers.length > 0 && (
                        <Form.Item label="选择会员" style={{ marginTop: 40 }}>
                            <div style={{ maxHeight: 300, overflowY: 'auto', border: '1px solid #d9d9d9', borderRadius: 6 }}>
                                {searchUsers.map(user => (
                                    <div
                                        key={user.id}
                                        className={`user-item ${selectedUser?.id === user.id ? 'selected' : ''}`}
                                        onClick={() => handleSelectUser(user)}
                                        style={{
                                            padding: '12px 16px',
                                            borderBottom: '1px solid #f0f0f0',
                                            cursor: 'pointer',
                                            backgroundColor: selectedUser?.id === user.id ? '#e6f7ff' : 'transparent',
                                            transition: 'background-color 0.2s'
                                        }}
                                    >
                                        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                                            <Avatar size={40} icon={<UserOutlined />} />
                                            <div style={{ flex: 1 }}>
                                                <div style={{ fontWeight: 500, marginBottom: 4 }}>
                                                    {user.username}
                                                </div>
                                                <div style={{ color: '#666', fontSize: 12 }}>
                                                    手机号: {user.mobile || '未设置'}
                                                </div>
                                                <div style={{ color: '#666', fontSize: 12 }}>
                                                    余额: ¥{user.balance.toFixed(2)} | 积分: {user.credit}
                                                </div>
                                            </div>
                                            {selectedUser?.id === user.id && (
                                                <div style={{ color: '#1890ff' }}>
                                                    ✓ 已选择
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </Form.Item>
                    )}

                    {selectedUser && (
                        <Form.Item label="已选择会员">
                            <div style={{
                                padding: 16,
                                backgroundColor: '#f6ffed',
                                border: '1px solid #b7eb8f',
                                borderRadius: 6,
                                display: 'flex',
                                alignItems: 'center',
                                gap: 12
                            }}>
                                <Avatar size={48} icon={<UserOutlined />} />
                                <div>
                                    <div style={{ fontWeight: 600, marginBottom: 4 }}>
                                        {selectedUser.username}
                                    </div>
                                    <div style={{ color: '#666', fontSize: 13 }}>
                                        手机号: {selectedUser.mobile || '未设置'}
                                    </div>
                                    <div style={{ color: '#666', fontSize: 13 }}>
                                        余额: ¥{selectedUser.balance.toFixed(2)} | 积分: {selectedUser.credit}
                                    </div>
                                </div>
                            </div>
                        </Form.Item>
                    )}
                </Form>
            </Modal>

            {/* 结账模态框 */}
            <Modal
                title="订单结账"
                open={checkoutModalVisible}
                onOk={handleCheckoutSubmit}
                onCancel={() => {
                    setCheckoutModalVisible(false);
                    setCheckoutPreview(null);
                }}
                confirmLoading={operationLoading}
                destroyOnClose
                width={600}
                okText="确认结账"
                cancelText="取消"
            >
                <Form
                    form={checkoutForm}
                    layout="vertical"
                    onValuesChange={() => {
                        // 表单值变化时重新预览
                        setTimeout(() => handleCheckoutPreview(), 100);
                    }}
                >
                    {order?.user && (
                        <>
                            <Form.Item
                                label="会员信息"
                            >
                                <div style={{
                                    padding: 12,
                                    backgroundColor: '#f6ffed',
                                    border: '1px solid #b7eb8f',
                                    borderRadius: 6,
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: 12
                                }}>
                                    <Avatar size={40} icon={<UserOutlined />} />
                                    <div>
                                        <div style={{ fontWeight: 500, marginBottom: 4 }}>
                                            {order.user.username}
                                        </div>
                                        <div style={{ color: '#666', fontSize: 13 }}>
                                            余额: ¥{order.user.balance.toFixed(2)} | 积分: {order.user.credit}
                                        </div>
                                    </div>
                                </div>
                            </Form.Item>

                            <Form.Item
                                name="useBalance"
                                valuePropName="checked"
                            >
                                <Checkbox>
                                    使用会员余额 (可用: ¥{order.user.balance.toFixed(2)})
                                </Checkbox>
                            </Form.Item>

                            <Form.Item
                                name="useCredit"
                                valuePropName="checked"
                            >
                                <Checkbox>
                                    使用会员积分 (可用: {order.user.credit}分)
                                </Checkbox>
                            </Form.Item>
                        </>
                    )}

                    <Form.Item
                        label="支付方式"
                        name="payMethod"
                        rules={[{ required: true, message: '请选择支付方式' }]}
                    >
                        <Radio.Group>
                            <Radio value="cash">现金支付</Radio>
                            <Radio value="card">刷卡支付</Radio>
                            <Radio value="wechat">微信支付</Radio>
                            <Radio value="alipay">支付宝</Radio>
                        </Radio.Group>
                    </Form.Item>

                    <Spin spinning={checkoutLoading}>
                        {checkoutPreview && (
                            <Form.Item label="结账预览">
                                <div className="checkout-preview">
                                    <div className="checkout-preview-item">
                                        <Text>订单原价:</Text>
                                        <Text className="checkout-preview-original">
                                            ¥{(checkoutPreview.amount + checkoutPreview.totalDeduction).toFixed(2)}
                                        </Text>
                                    </div>
                                    {checkoutPreview.balanceDeduction > 0 && (
                                        <div className="checkout-preview-item">
                                            <Text>余额抵扣:</Text>
                                            <div className="checkout-preview-deduction">
                                                <div>-¥{checkoutPreview.balanceDeduction.toFixed(2)}</div>
                                                <div className="checkout-preview-deduction-detail">
                                                    使用余额: ¥{checkoutPreview.usedBalance.toFixed(2)}
                                                </div>
                                            </div>
                                        </div>
                                    )}
                                    {checkoutPreview.creditDeduction > 0 && (
                                        <div className="checkout-preview-item">
                                            <Text>积分抵扣:</Text>
                                            <div className="checkout-preview-deduction">
                                                <div>-¥{checkoutPreview.creditDeduction.toFixed(2)}</div>
                                                <div className="checkout-preview-deduction-detail">
                                                    使用积分: {checkoutPreview.usedCredit}分
                                                </div>
                                            </div>
                                        </div>
                                    )}
                                    {checkoutPreview.totalDeduction > 0 && (
                                        <div className="checkout-preview-item">
                                            <Text>总抵扣:</Text>
                                            <Text className="checkout-preview-total-deduction">
                                                -¥{checkoutPreview.totalDeduction.toFixed(2)}
                                            </Text>
                                        </div>
                                    )}
                                    <div className="checkout-preview-item">
                                        <Text strong>实付金额:</Text>
                                        <Text strong className="checkout-preview-total">
                                            ¥{checkoutPreview.amount.toFixed(2)}
                                        </Text>
                                    </div>
                                </div>
                            </Form.Item>
                        )}
                    </Spin>
                </Form>
            </Modal>
        </Layout>
    );
};

export default OrderDetailPage; 